<?php

/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use app\common\model\club\User;
use app\common\model\Message;
use \GatewayWorker\Lib\Gateway;
use think\Db;
use think\Env;

require_once 'Connection.php';
/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static $db = null;
    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        $host = 'rm-2vch0cv5pqb02j80e9o.mysql.cn-chengdu.rds.aliyuncs.com';
        $port = '';
        $user = 'php';
        $password = 'phpstudy';
        $db_name = '1331';
        self::$db = new \Workerman\MySQL\Connection($host, $port, $user, $password, $db_name);
    }
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        Gateway::sendToClient($client_id, json_encode([
            'type' => 'init',
            'client_id' => $client_id,
            'time' => date('Y-m-d H:i:s')
        ]));
        // // 向所有人发送
        // Gateway::sendToAll("$client_id login\r\n");
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        // 向所有人发送 
        // Gateway::sendToAll("$client_id said $message\r\n");
        $time = time();
        $req_data = json_decode($message, true);
        $content['content'] = $req_data['content'];
        $content['time'] = date('Y-m-d H:i:s', $time);
        $content['type'] = $req_data['type'];
        if ($req_data['type'] == 'bind') {
            $client = Gateway::getClientIdByUid($req_data['uid']);
            if ($client) {
                foreach ($client as $vv) {
                    Gateway::closeClient($vv);
                }
            }
            // $message = '{"type":"bind","uid":"1"}';
            //绑定用户uid
            Gateway::bindUid($client_id, $req_data['uid']);
            Gateway::joinGroup($client_id, 'group_1');
        }
        if ($req_data['type'] == 'location') {
            // $message = '{"type":"location",'lng':'1111111','lat':'2222222'}';
            $uid = Gateway::getUidByClientId($client_id);
            self::$db->update('fa_user')->cols(array('lng' => $req_data['lng'], 'lat' => $req_data['lat']))->where('id=' . $uid)->query();
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 向所有人发送 
        // GateWay::sendToAll("$client_id logout\r\n");
    }
}
